package com.ztman.service.work.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ztman.basic.context.ContextUtil;
import com.ztman.basic.exception.BizException;
import com.ztman.basic.model.RemoteData;
import com.ztman.basic.utils.SpringUtils;
import com.ztman.service.authority.entity.auth.Role;
import com.ztman.service.authority.entity.auth.User;
import com.ztman.service.authority.entity.auth.UserRole;
import com.ztman.service.authority.entity.core.Org;
import com.ztman.service.authority.service.auth.RoleService;
import com.ztman.service.authority.service.auth.UserRoleService;
import com.ztman.service.authority.service.auth.UserService;
import com.ztman.service.authority.service.core.OrgService;
import com.ztman.service.authority.service.core.StationService;
import com.ztman.service.work.entity.*;
import com.ztman.service.work.service.*;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: wsd
 * @date: 2021/9/1 9:08
 */
public class StateController {
    private UserService userService = null;
    private StationService stationService = null;
    private RoleService roleService = null;
    private UserRoleService userRoleService = null;
    private WorkOrderTplDataService workOrderTplDataService = null;
    private OrgService orgService = null;
    private WorkOrderInfoService workOrderInfoService = null;
    private TplInfoService tplInfoService = null;
    private WorkOrderCirculationHistoryService workOrderCirculationHistoryService = null;
    private ProcessInfoService processInfoService = null;
    private JSONArray nodes = null;
    StateController(UserService userService){
        this.userService = userService;
    }
    StateController(JSONArray nodes){
        this.nodes = nodes;
    }
    StateController(UserService userService,WorkOrderInfoService workOrderInfoService){
        this.userService = userService;
        this.workOrderInfoService = workOrderInfoService;
    }
    StateController(StationService stationService){
        this.stationService = stationService;
    }
    StateController(RoleService roleService){
        this.roleService = roleService;
    }
    StateController(UserService userService,RoleService roleService){
        this.userService = userService;
        this.roleService = roleService;
    }
    StateController(UserService userService,RoleService roleService,StationService stationService){
        this.userService = userService;
        this.roleService = roleService;
        this.stationService = stationService;
    }
    StateController(RoleService roleService,StationService stationService){
        this.roleService = roleService;
        this.stationService = stationService;
    }

    public StateController(UserService userService,UserRoleService userRoleService, WorkOrderInfoService workOrderInfoService, ProcessInfoService processInfoService,WorkOrderCirculationHistoryService workOrderCirculationHistoryService) {
        this.userService = userService;
        this.workOrderInfoService = workOrderInfoService;
        this.processInfoService = processInfoService;
        this.userRoleService = userRoleService;
        this.workOrderCirculationHistoryService = workOrderCirculationHistoryService;
    }

    public StateController(UserService userService, UserRoleService userRoleService, RoleService roleService, OrgService orgService) {
        this.userService = userService;
        this.roleService = roleService;
        this.orgService = orgService;
        this.userRoleService = userRoleService;
    }

    public StateController(TplInfoService tplInfoService,UserService userService, UserRoleService userRoleService, WorkOrderInfoService workOrderInfoService, ProcessInfoService processInfoService, WorkOrderTplDataService workOrderTplDataService, WorkOrderCirculationHistoryService workOrderCirculationHistoryService) {
        this.userService = userService;
        this.tplInfoService = tplInfoService;
        this.workOrderInfoService = workOrderInfoService;
        this.processInfoService = processInfoService;
        this.userRoleService = userRoleService;
        this.workOrderCirculationHistoryService = workOrderCirculationHistoryService;
        this.workOrderTplDataService = workOrderTplDataService;

    }

    public StateController(UserService userService, OrgService orgService) {
        this.userService = userService;
        this.orgService = orgService;
    }

    public StateController(UserService userService, RoleService roleService, OrgService orgService) {
        this.userService = userService;
        this.orgService = orgService;
        this.roleService = roleService;
    }

    public List getUserArrayName(String[] ids,String processMethod) {
        List<String> nameList = new ArrayList<>();

        if ("person".equals(processMethod)) {
            if(userService == null){
                return new ArrayList();
            }
            List<String> longs = Arrays.asList(ids);
            List<Long> idss = longs.stream().mapToLong(num -> {
                return Long.valueOf(num);
            }).boxed().collect(Collectors.toList());

            List<User> userById = userService.findUserById(idss);
            nameList = userById.stream().map(User::getName).collect(Collectors.toList());
        }
        if ("role".equals(processMethod)) {
            if(roleService == null){
                return new ArrayList();
            }
            List<String> longs = Arrays.asList(ids);
            List<Long> idss = longs.stream().mapToLong(num -> {
                return Long.valueOf(num);
            }).boxed().collect(Collectors.toList());

            List<Role> roleList = roleService.listByIds(idss);
            nameList = roleList.stream().map(Role::getName).collect(Collectors.toList());
        }
        if ("department".equals(processMethod)) {
            if(userService == null){
                return new ArrayList();
            }
            List<String> longs = Arrays.asList(ids);
            List<Long> idss = longs.stream().mapToLong(num -> {
                return Long.valueOf(num);
            }).boxed().collect(Collectors.toList());

            List<Org> userById = orgService.listByIds(idss);
            nameList = userById.stream().map(Org::getLabel).collect(Collectors.toList());
        }
        if ("variable".equals(processMethod)) {
            if(userService == null){
                return new ArrayList();
            }
            for (int i = 0; i < ids.length; i++) {
                if (Integer.parseInt(ids[i])==1) {
                    nameList.add("创建者");
                }
                if(Integer.parseInt(ids[i])==2){
                    nameList.add("创建者负责人");
                }
            }
        }

        return nameList;
    }
    public HashMap ProcessStructure(Long processId, Long workOrderId){
        HashMap resultMap = new HashMap();
        ProcessInfo processInfoValue = processInfoService.getById(processId);
        if (processInfoValue.getStructure().size() > 0) {
            JSONArray nodes = processInfoValue.getStructure().getJSONArray("nodes");
            //冒泡排序
            for (int i = 0; i < nodes.size(); i++) {
                for (int j = 1; j < nodes.size()-i; j++) {
                    if(nodes.getJSONObject(j).getInteger("sort")==null ||
                            nodes.getJSONObject(j-1).getInteger("sort")== null){
                        throw  new BizException("流程未定义顺序属性，请确认");
                    }
                    int leftJsonSort = nodes.getJSONObject(j).getIntValue("sort");
                    int rightJsonSort = nodes.getJSONObject(j-1).getIntValue("sort");

                    if (leftJsonSort < rightJsonSort) {
                        JSONObject temp = new JSONObject();
                        JSONObject temp2 = new JSONObject();
                        temp.putAll(nodes.getJSONObject(j));
                        temp2.putAll(nodes.getJSONObject(j - 1));
                        nodes.getJSONObject(j).clear();
                        nodes.getJSONObject(j).putAll(temp2);
                        nodes.getJSONObject(j - 1).clear();
                        nodes.getJSONObject(j - 1).putAll(temp);
                    }
                }
            }

            resultMap.put("process", processInfoValue);
            resultMap.put("nodes", nodes);
            resultMap.put("edges", processInfoValue.getStructure().getJSONArray("edges"));

            //获取历史记录
            List<WorkOrderCirculationHistory> workOrderCirculationHistoryList = workOrderCirculationHistoryService.list(new QueryWrapper<>(new WorkOrderCirculationHistory())
                    .eq("work_order", workOrderId).orderByDesc("id"));
            resultMap.put("circulationHistory", workOrderCirculationHistoryList);

            if(workOrderId==0){
                JSONArray tpls = processInfoValue.getTpls();
                List<Long> longs = tpls.toJavaList(Long.class);
                List<TplInfo> tplInfos = tplInfoService.listByIds(longs);
                resultMap.put("tpls", tplInfos);
            }else{
                //查询工单信息
                WorkOrderInfo workOrderInfo = workOrderInfoService.getById(workOrderId);
                if (workOrderInfo != null) {
                    JSONArray stateList = workOrderInfo.getState();
                    if(stateList.size()==0){
                        throw new BizException("当前工单没有下一节点数据");
                    }
                    //整里需要并行处理的数据
                    if(stateList.size() > 1){
                        continueHistoryTag:
                        for (int i = 0; i < workOrderCirculationHistoryList.size(); i++) {
                            boolean status = false;
                            WorkOrderCirculationHistory history = workOrderCirculationHistoryList.get(i);
                            for (int j = 0; j < stateList.size(); j++) {
                                JSONObject stateJSONObject = stateList.getJSONObject(j);
                                if(history.getSource().equals(stateJSONObject.getString("id"))){
                                    status = true;
                                    stateList.addAll(stateList.subList(j, stateList.size()));
                                    continue continueHistoryTag;
                                }
                            }
                            if(!status){
                                break;
                            }
                        }
                    }

                    if(stateList.size() > 0 ){
                        breakStateTag:
                        for (int i = 0; i < stateList.size(); i++) {
                            JSONObject stateJson = stateList.getJSONObject(i);
                            if(nodes != null){
                                for (int j = 0; j < nodes.size(); j++) {
                                    JSONObject nodeJson = nodes.getJSONObject(j);
                                    if(stateJson.getString("id").equals(nodeJson.getString("id"))){
                                        JSONArray processor = stateJson.getJSONArray("processor");
                                        if (processor != null) {
                                            List<Long> processorList = processor.toJavaList(Long.class);
                                            for (Long id : processorList) {
                                                if (id.equals(ContextUtil.getUserId())) {
                                                    workOrderInfo.setCurrentState(stateJson.getString("id"));
                                                    break breakStateTag;
                                                }
                                            }
                                        } else {
                                            throw new BizException("为查询到处理人，请确认");
                                        }
                                    }

                                }
                            }
                        }
                        if (StringUtils.isEmpty(workOrderInfo.getCurrentState())) {
                            workOrderInfo.setCurrentState(stateList.getJSONObject(0).getString("id"));
                        }
                    }
                    resultMap.put("workOrder", workOrderInfo);
                    List<WorkOrderTplData> work_order = workOrderTplDataService.list(new QueryWrapper<>(new WorkOrderTplData()).eq("work_order", workOrderId));
                    resultMap.put("tpls", work_order);
                }
            }
        }
        return resultMap;
    }
    public Boolean JudgeUserAuthority(Long workOrderId,String currentState){
        String  name = ContextUtil.getName();
        Long userId = ContextUtil.getUserId();
        // 获取工单信息
        WorkOrderInfo workOrderInfo = workOrderInfoService.getById(workOrderId);


        User currentUserInfo = userService.getById(userId);
        //获取系统用户信西
        UserRole userRoleSystem = new UserRole();
        userRoleSystem.setUserId(userId);
        List<UserRole> systemRoleUser = userRoleService.list((new QueryWrapper<>(userRoleSystem)));
        List<Long> userRoleSystemUser = systemRoleUser.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        if(currentUserInfo == null){
            throw  new BizException("未获取到用户信息");
        }
        JSONObject currentStateValue = new JSONObject();
        if(BeanUtil.isNotEmpty(workOrderId)){
            ProcessInfo processInfo = processInfoService.getProcessInfoById(workOrderInfo.getProcess());
            if(processInfo.getStructure()!= null){
                JSONObject structure = processInfo.getStructure();
                nodes =  structure.getJSONArray("nodes");
                ProcessState processState = new ProcessState(nodes);
                JSONObject stateValue = processState.getNode(currentState);
                if (stateValue != null) {
                    JSONArray currentStateList = workOrderInfo.getState();
                    if(currentStateList != null){
                        for (int i = 0; i < currentStateList.size(); i++) {
                            JSONObject jsonObject = currentStateList.getJSONObject(i);
                            if (jsonObject.getString("id").equals(currentState)) {
                                currentStateValue.putAll(jsonObject);
                            }
                        }
                        //会签
                        if(currentStateValue.getJSONArray("processor") != null && currentStateValue.getJSONArray("processor").size() > 0){
                            if(stateValue.getBoolean("isCounterSign")!=null && stateValue.getBoolean("isCounterSign")){
                                List<WorkOrderCirculationHistory> circulationHistoryList =  workOrderCirculationHistoryService
                                                                                                                .lambdaQuery()
                                                                                                                .select()
                                                                                                                .eq(WorkOrderCirculationHistory::getWorkOrder, workOrderId)
                                                                                                                .orderBy(true, false).list();
                                if(circulationHistoryList==null){
                                    return null;
                                }
                                for (int i = 0; i < circulationHistoryList.size(); i++) {
                                    WorkOrderCirculationHistory cirHistoryValue = circulationHistoryList.get(i);
                                    if(!cirHistoryValue.getSource().equals(stateValue.getString("id"))){
                                        break;
                                    } else if (cirHistoryValue.getSource().equals(stateValue.getString("id"))) {

                                        if ("person".equals(currentStateValue.getString("process_method"))) {
                                            // 验证个人会签
                                            if (cirHistoryValue.getProcessorId().equals(ContextUtil.getUserId())) {
                                                return null;
                                            }
                                        } else if ("role".equals(currentStateValue.getString("process_method"))) {
                                            // 验证角色会签  ????
                                            if (stateValue.getBooleanValue("fullHandle")) {
                                                return null;
                                            }else {
                                                UserRole userRole = new UserRole();
                                                userRole.setUserId(cirHistoryValue.getProcessorId());
                                                List<UserRole> processorIdUser = userRoleService.list((new QueryWrapper<>(userRole)));
                                                List<Long> collect = processorIdUser.stream().map(UserRole::getRoleId).collect(Collectors.toList());
                                                if (processorIdUser != null && collect.contains(userRoleSystemUser)) {
                                                    for (int j = 0; j < collect.size(); j++) {
                                                        if ( userRoleSystemUser.contains(collect.get(i))) {
                                                           return null;
                                                        }
                                                    }
                                                }
                                            }
                                        } else if ("department".equals(currentStateValue.getString("process_method"))) {
                                            //部门会签
                                            if (stateValue.getBooleanValue("fullHandle")) {
                                                return null;
                                            }else {
                                                //cirHistoryValue processId 用户信息
                                                User processIdUser = userService.getById(cirHistoryValue.getProcessorId());
                                                if(processIdUser==null){
                                                    return null;
                                                }
                                                if(processIdUser.getStation().equals(currentUserInfo.getOrg().getKey())){
                                                        return null;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        switch (currentStateValue.getString("process_method")) {
            case "person":
                if (currentStateValue.getJSONArray("processor").contains(String.valueOf(userId))) {
                    return true;
                }
                break;
            case "role":
                JSONArray processor = currentStateValue.getJSONArray("processor");
                for (int i = 0; i < processor.size(); i++) {
                    if (userRoleSystemUser.contains(processor.getLong(i))) {
                        return  true;
                    }
                }
                break;
            case "department":
                if (currentStateValue.getJSONArray("processor").contains(currentUserInfo.getOrg().getKey())) {
                    return true;
                }
                break;
            case "variable":
                JSONArray process = currentStateValue.getJSONArray("processor");
                for (int i = 0; i < process.size(); i++) {
                    if(process.getInteger(i)==1){
                        if(workOrderInfo.getCreatedBy().equals(userId)){
                            return true;
                        }
                    }
                    if(process.getInteger(i)==2){
                        User user = userService.getById(workOrderInfo.getCreatedBy());
                        OrgService orgService = SpringUtils.getBean(OrgService.class);
                        Org org = orgService.getById(user.getOrg().getKey());
                        if(org.getParentId().equals(currentUserInfo.getOrg())){
                            return true;
                        }
                    }
                }
                break;
            default:
                break;
        }
        return false;
    }


    public List<User> GetPrincipalUserInfo(JSONArray state,Long createdBy) {
        List resultList = new ArrayList();
        if(state.size()>0){
            User createByUserDetails = userService.getById(createdBy);
            for (int i = 0; i < state.size(); i++) {
                JSONObject jsonObject = state.getJSONObject(i);
                if(jsonObject.getJSONArray("processor")== null || jsonObject.getJSONArray("processor").size() == 0){
                    throw new BizException("未找到对应的处理人，请取人");
                }
                JSONArray processor = jsonObject.getJSONArray("processor");
                Long[] processorListSize = new Long[processor.size()];
                Long[] processorLongArray = processor.toArray(processorListSize);
                List<Long> processorList = Arrays.asList(processorLongArray);
                String processMethod = jsonObject.getString("process_method");
                if ("person".equals(processMethod)) {
                    if(userService == null){
                        return new ArrayList();
                    }
                    List<User> userById = userService.findUserById(processorList);
                    return userById;
                }
                if ("role".equals(processMethod)) {
                    if(roleService == null){
                        return new ArrayList();
                    }
                    List<UserRole> userRoles = userRoleService.listByIds(processorList);
                    List<Long> userIds = userRoles.stream().map(UserRole::getUserId).collect(Collectors.toList());
                    List<User> users = userService.listByIds(userIds);
                    return users;
                }
                if ("department".equals(processMethod)) {
                    if(userService == null){
                        return new ArrayList();
                    }
                    List<User> deptUser = userService.findUserByOrgIds(processorList);
                    return deptUser;
                }
                if ("variable".equals(processMethod)) {
                    if(userService == null){
                        return new ArrayList();
                    }
                    for (int j = 0; j < processorList.size(); j++) {
                        Long varibaleValue = processorList.get(i);
                        if (varibaleValue==1){
                            resultList.add(createByUserDetails);
                        }
                        if(varibaleValue==2){
                            Org org = orgService.getById(varibaleValue);
                            //如果是最高领导，添加最高领导
                            if(org.getParentId()==0){
                                User user = new User();
                                user.setOrg(new RemoteData<>(varibaleValue));
                                List<User> list = userService.list(new QueryWrapper<>(user));
                                resultList.addAll(list);
                            }else{
                                User user = new User();
                                user.setOrg(new RemoteData<>(org.getParentId()));
                                List<User> list = userService.list(new QueryWrapper<>(user));
                                resultList.addAll(list);
                            }

                        }
                    }
                }

            }


        }
        return new ArrayList<>();
    }
    public void GetVariableValue(JSONArray stateList,Long creator){
        for (int i = 0; i < stateList.size(); i++) {
            JSONObject jsonObject = stateList.getJSONObject(i);
            if(jsonObject.getString("process_method") != null && jsonObject.getString("process_method").equals("variable")){
                JSONArray processor = jsonObject.getJSONArray("processor");
                int size = processor.size();
                for (int j = 0; j < size; j++) {
                    Long processorLong = processor.getLong(i);
                    if (processorLong == 1) {
                        //创建者
                        processor.add(j, creator);
                    }else{
                        //1.查询用户信息
                        User user = userService.getById(creator);
                        //2.查询部门信息
                        Org org = orgService.getById(user.getOrg().getKey());
                        //3.替换处理人信息
                        //之后修改 部门增加上部门负责人字段(未开发玩完)
                        if(org.getParentId()==0){
                            processor.add(j, creator);
                        }else{
                            processor.add(j, org.getCreatedBy());
                        }

                    }
                }
                jsonObject.put("process_method", "person");
            }
        }
    }
}






































































